-
Notifications
You must be signed in to change notification settings - Fork 15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Premier essai (NE PAS MERGER!!!) #224
base: main
Are you sure you want to change the base?
Conversation
Ça marche pas encore tout à fait... j'arrive à avoir l'URL du devicehub mais pas du challengehub je comprends pas pourquoi. Si quelqu'un veut s'éssayer avec ça
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The code updates introduce new structures and methods for handling websocket connections which enhance scalability by allowing multiple websocket clients. The implementation of a WebsocketManager is a good design choice for managing resources shared between websockets. However, some elements like the commented-out websocket initialization in the API should be clarified or removed, and the complexity of the refresh logic could be reduced for better code clarity.
Positives:
- Effective use of dataclasses for websocket configurations.
- Clear separation of concerns with the WebsocketManager handling initialization and token refresh functionality.
Areas of Improvement:
- Clarify or remove commented-out code in websocket initialization to avoid confusion.
- Consider separating token acquisition and reuse logic to improve code readability.
pyhilo/websocket.py
Outdated
# ic-dev21 reuse it for challenge hub | ||
await self.refresh_token(self.challengehub, get_new_token=False) | ||
|
||
async def refresh_token(self, config: WebsocketConfig, get_new_token: bool = True) -> None: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The use of get_new_token
flag might lead to overly complex logic branches. Consider refactoring to separate methods for obtaining new tokens and reusing tokens to improve clarity and maintenance.
J'arrive à la négociation du challengehub, chose qui ne se produisait pas avant, merci à @Leicas pour la suggestion. J'ai sorti le token du if pour y avoir accès dans la fonction au complet. Ça marche toujours pas, mais je pense que c'est un pas dans la bonne direction
Keeping the right tokens for every websocket connection
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The code introduces improvements in managing multiple websocket connections by implementing a WebsocketManager
to handle shared access tokens and connection parameters. The changes enhance modularity and support for new endpoints. However, some redundant code can be optimized, and string-dependent logic needs revision for robustness.
Positives:
- The introduction of
WebsocketConfig
andWebsocketManager
provides a clean and organized approach to managing multiple websocket connections. - The use of data class
WebsocketConfig
enhances readability and maintainability of the connection parameters.
Areas of Improvement:
- Reduce redundancy by optimizing access token retrieval in the
API
class. - Replace string comparisons with a more robust approach to managing websocket endpoint mappings to prevent potential errors if endpoint names change in the future.
pyhilo/websocket.py
Outdated
state_key = ( | ||
"websocket" | ||
if config.endpoint == "AUTOMATION_DEVICEHUB_ENDPOINT" | ||
else "websocket2" | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The logic for determining the state_key
here is dependent on string comparison of endpoint names. This can become error-prone if endpoint names change. Consider using a more robust method of differentiating the websocket types, possibly by leveraging enumeration or a mapping approach.
state_key = ( | |
"websocket" | |
if config.endpoint == "AUTOMATION_DEVICEHUB_ENDPOINT" | |
else "websocket2" | |
) | |
endpoint_mapping = { | |
"AUTOMATION_DEVICEHUB_ENDPOINT": "websocket", | |
"AUTOMATION_CHALLENGE_ENDPOINT": "websocket2" | |
} | |
state_key = endpoint_mapping.get(config.endpoint, "unknown") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The changes introduce a new WebsocketManager for handling multiple websocket connections and integrate logic to handle specific endpoint scenarios, such as for the AUTOMATION_CHALLENGE_ENDPOINT. Overall, the refactoring towards a more object-oriented approach with the introduction of WebsocketManager is commendable; it enhances modularity and code maintainability. However, potential areas for improvement include adding proper error handling mechanisms and more detailed documentation to explain specific logic adjustments, such as header manipulation based on the endpoint.
Positives:
- The introduction of a WebsocketManager improves the organization and scaling of the websocket handling logic, facilitating better maintenance and extension capabilities.
- The code adopts type hints across new methods, which increases code readability and helps in understanding the expected inputs and outputs.
Areas of Improvement:
- Enhance error handling to manage unexpected responses or network issues during websocket negotiation.
- Additional documentation and comments should be provided where headers are modified based on specific endpoints to explain the reasoning behind such changes.
# ic-dev21 trying Leicas suggestion | ||
if endpoint.startswith(AUTOMATION_CHALLENGE_ENDPOINT): | ||
# remove Ocp-Apim-Subscription-Key header to avoid 401 error | ||
kwargs["headers"].pop("Ocp-Apim-Subscription-Key", None) | ||
kwargs["headers"]["authorization"] = f"Bearer {access_token}" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Removing the 'Ocp-Apim-Subscription-Key' header when the endpoint is 'AUTOMATION_CHALLENGE_ENDPOINT' might introduce issues if this header is required elsewhere in the system. It's crucial to document this change within the function's docstring or as comments explaining the broader context and its necessity.
# ic-dev21 trying Leicas suggestion | |
if endpoint.startswith(AUTOMATION_CHALLENGE_ENDPOINT): | |
# remove Ocp-Apim-Subscription-Key header to avoid 401 error | |
kwargs["headers"].pop("Ocp-Apim-Subscription-Key", None) | |
kwargs["headers"]["authorization"] = f"Bearer {access_token}" | |
// Consider adding more comments or documentation here to explain why removing the header is necessary |
ça fonctionne comme ça, reste à modifier côté intégration home assistant
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The code effectively restructures the existing websocket client management by introducing a WebsocketManager and WebsocketConfig class to manage multiple websocket connections. This encapsulates the logic for connection negotiation and token management, making it easier to extend and maintain. The code also refines access to the web resources by qualifying endpoints with specific handling for headers.
Positives:
- The introduction of WebsocketManager and WebsocketConfig organizes the websocket connection management, enhancing maintainability.
- Proper use of async/await constructs is visible, promoting non-blocking I/O operations which is crucial for scalability.
Areas of Improvement:
- Consider lazy logging techniques for debug messages that are written using f-strings.
- Ensure query parameters in f-strings are properly encoded to prevent potential security issues.
LOG.debug(f"Getting websocket url for {config.endpoint}") | ||
url = f"{config.endpoint}/negotiate" | ||
LOG.debug(f"Negotiate URL is {url}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
String interpolation with f-strings for logging is generally fine for lower volume messages, but be mindful if this was a high-volume statement as it could have a performance impact. Consider lazy logging if performance becomes a concern.
Respect Black, remove unused imports
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The code introduces significant changes to websocket management by integrating a new WebsocketManager
class. This change aims to improve the management and negotiation of websocket connections by centralizing token refresh logic. While the code generally maintains clean and organized, the overall reliance on configuration comments as TODOs may affect legibility.
Positives:
- The refactoring towards a centralized
WebsocketManager
makes handling multiple websocket connections more scalable and manageable. - Logging practices are well-integrated, providing traceability which is important for debugging async operations in websocket handling.
Areas of Improvement:
- Consider consolidating commented-out code once its purpose has been replaced or is no longer needed after sufficient testing.
- Ensure comprehensive test coverage for the websocket negotiation to prevent regressions in live environments.
better logs to see which ws is doing what.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
Overall, the refactoring towards using the WebsocketManager pattern is a positive step towards better structuring of the websocket management logic. However, there are areas where potential redundancy or code bloat can be minimized, and some minor inefficiencies can be cleaned up. These modifications would enhance code maintainability and clarity.
Positives:
- The addition of WebsocketManager streamlines multiple websocket management, making the code more modular and maintainable.
- The inclusion of comprehensive logging details aids in debugging and traceability.
Areas of Improvement:
- Consider refining token management to avoid unnecessary duplicate requests.
- Clean up import statements by removing unused modules to enhance code cleanliness.
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple | ||
from urllib import parse |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is an unused import 'parse' which might have been intended for use in the module 'urllib'. Consider removing it to clean up unused imports and prevent confusion.
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple | |
from urllib import parse | |
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple |
pyhilo/websocket.py
Outdated
resp = await self.async_request( | ||
"post", | ||
f"{uri.path}negotiate?{uri.query}", | ||
host=uri.netloc, | ||
headers={ | ||
"authorization": f"Bearer {config.token}", | ||
}, | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The use of 'resp.get("connectionId")' without a default could lead to potential KeyError. Consider using a default value to safeguard against missing dictionary keys.
resp = await self.async_request( | |
"post", | |
f"{uri.path}negotiate?{uri.query}", | |
host=uri.netloc, | |
headers={ | |
"authorization": f"Bearer {config.token}", | |
}, | |
) | |
config.connection_id = resp.get("connectionId", "") |
…thon-hilo into WebsocketManagerClass
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The code introduces new websocket management functionality, including a new WebsocketManager class to handle multiple websocket connections. This change seems to enhance the functionality by separating concerns and managing different websocket endpoints with shared resources.
Positives:
- The use of a separate class to manage web sockets is a good design decision as it promotes separation of concerns and improves the modularity of the codebase.
- Consistent usage of coroutines and asynchronous requests, allowing for non-blocking operations and better performance in network operations.
Areas of Improvement:
- Consolidate similar conditional header logic into reusable functions to reduce complexity and improve code maintainability.
- Add error handling for URL parsing to prevent potential runtime exceptions which could cause service disruptions.
if endpoint.startswith(AUTOMATION_CHALLENGE_ENDPOINT): | ||
# remove Ocp-Apim-Subscription-Key header to avoid 401 error | ||
kwargs["headers"].pop("Ocp-Apim-Subscription-Key", None) | ||
kwargs["headers"]["authorization"] = f"Bearer {access_token}" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handling different authorization methods for various endpoints in the same function increases complexity and potential for errors. Consider extracting this logic into a separate function to improve readability and maintainability.
if endpoint.startswith(AUTOMATION_CHALLENGE_ENDPOINT): | |
# remove Ocp-Apim-Subscription-Key header to avoid 401 error | |
kwargs["headers"].pop("Ocp-Apim-Subscription-Key", None) | |
kwargs["headers"]["authorization"] = f"Bearer {access_token}" | |
# Define a new function to handle request headers | |
def add_authorization_headers(endpoint, headers): | |
if endpoint.startswith(API_REGISTRATION_ENDPOINT): | |
headers.update(API_REGISTRATION_HEADERS) | |
elif endpoint.startswith(FB_INSTALL_ENDPOINT): | |
headers.update(FB_INSTALL_HEADERS) | |
elif endpoint.startswith(ANDROID_CLIENT_ENDPOINT): | |
headers.update(ANDROID_CLIENT_HEADERS) | |
if endpoint.startswith(AUTOMATION_CHALLENGE_ENDPOINT): | |
headers.pop("Ocp-Apim-Subscription-Key", None) |
This reverts commit 465e2ff.
revenu à full_ws_url pour garder le même nom que le code original
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The code introduces a WebsocketManager
class allowing for handling multiple websocket connections, which is a significant architectural improvement for managing complex websocket interactions. Minor in-line adjustments such as header management are also included. Ensure comprehensive testing, especially with the new class, to validate its interaction with existing parts of the system.
Positives:
- Modular design with the addition of WebsocketManager enhances scalability.
- Improved logging for web socket connections which assists in debugging.
Areas of Improvement:
- Consider revisiting the decision to remove specific headers for certain endpoints to ensure all use cases are covered and logs are checked post-deployment.
- Refactor the initialization method of
WebsocketManager
to reduce parameter complexity, which will improve maintainability.
Il y avait un string literal donc websocket ne se faisait pas remplir, websocket2 oui. Retrait et modification de quelques commentaires
e750453
to
5659b41
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The recent changes incorporate a new endpoint for the 'ChallengeHub', and significant refactor on how websocket connections are managed within the system through a newly introduced WebsocketManager class. This refactoring enhances modularity and maintainability, especially useful when managing multiple websocket connections. However, there are opportunities to optimize performance by minimizing unnecessary API token calls, and ensure robustness by validating the existence of attributes before reference.
Positives:
- Refactor introduces a WebsocketManager class, promoting better abstraction and separation of concerns.
- Meaningful debug logs added to trace the websocket connections simplifying troubleshooting efforts.
Areas of Improvement:
- Delay access token retrieval until it is confirmed needed to reduce overhead.
- Validate critical attributes before usage to prevent runtime errors.
Le post se fait maintenant dans websocket.py, dead code
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The code introduces a new WebsocketManager to manage multiple websocket connections with appropriate configurations. It includes a refactoring of token and negotiation logic, as well as logging enhancements for better traceability. Improvements in manageability and support for additional websocket connections are notable.
Positives:
- Refactoring the websocket connection logic into a dedicated WebsocketManager class enhances readability and maintainability.
- The use of Python's type hinting improves code clarity and future-proofing for developers working with the codebase.
Areas of Improvement:
- Ensure consistent logging practices across all websocket operations to facilitate easier debugging and traceability.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The recent changes introduce a WebsocketManager class, improving the project's structure by separating concerns related to websocket management from other functionalities. Code readability and organization have generally been enhanced. However, there's still a need to ensure that new endpoint-specific logic is modular and decoupled to avoid single-point maintenance complexity.
Positives:
- The introduction of WebsocketManager centralizes management of websocket connections, promoting scalability and maintainability.
- Enhancements in logging provide more context-specific information, aiding debugging efforts significantly.
Areas of Improvement:
- Consider decoupling endpoint-specific logic from general request methods to enhance code maintainability and testability.
- Documentation for new classes and methods could be more detailed to ensure clear understanding of their roles and responsibilities.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The refactored code introduces a more structured approach to handling websocket connections by using a new WebsocketManager class, which improves modularity and potentially eases the addition of new websockets in the future. However, there are areas that require attention, such as proper documentation for new class attributes and constructors, and ensuring that resource management, particularly for asynchronous sessions, is handled correctly.
Positives:
- The extraction of websocket management into a dedicated class increases code reusability and readability.
- Using type annotations provides better clarity on expected data types throughout the codebase.
Areas of Improvement:
- Ensure thorough documentation for newly introduced classes and methods to assist future developers in understanding and maintaining the code.
- Review logging practices to avoid exposing sensitive information in production environments.
###🚧 Blocking Issues:
- The session management lacks validation or lifecycle management, which could lead to unhandled exceptions or resource leaks. This needs to be addressed to ensure robust and error-free execution.
Pour faire changement
Renommé pour être plus facile à suivre.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The code introduces a clean refactor by centralizing websocket management into a new WebsocketManager
class. This enhances clarity and separation of concerns, and likely reduces code duplication related to websocket handling. The use of data classes for configuration is appropriate and makes the codebase more maintainable and scalable. Attention to thread safety with locks and state management via YAML shows robustness in design.
Positives:
- Refactored websocket handling into a
WebsocketManager
class that encapsulates all websocket-related logic, improving modularity. - Use of
dataclass
forWebsocketConfig
improves readability and manageability of configuration settings.
Areas of Improvement:
- Consider initializing instance variables with either default values or placeholders (like
None
) at the beginning of a class to avoid unexpected AttributeError if accessed before assignment. - Enhance logging by including method names or additional context to provide more informative debug messages.
Clarifier un peu
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review for this PR
The refactor introduces a WebsocketManager class to handle multiple websocket connections, and leverages a dataclass for websocket configuration. This improves organization and separation of concerns. However, movement of common configuration classes to separate modules could be beneficial for modularity. Some instance variables in API are unused, suggesting a need for cleanup or explanation of future intent. Overall, the changes align with a modular design approach, though further decomposition of WebsocketManager could enhance testability and maintainability.
Areas of Improvement:
- Ensure that all defined attributes are used or document their intended future use.
- Consider simplifying the WebsocketManager constructor to adhere to the Single Responsibility Principle.
Ça marche pas encore tout à fait... j'arrive à avoir l'URL du devicehub mais pas du challengehub je comprends pas pourquoi.
Si quelqu'un veut s'éssayer avec ça